package com.qiu.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiu.demo.entity.User;
import com.qiu.demo.enums.HttpCodeEnum;
import com.qiu.demo.util.JsonResult;
import com.qiu.demo.util.TokenUtil;

import cn.hutool.core.lang.UUID;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/common")
@CrossOrigin
public class CommonController {

    private final String URL = "http://localhost:8080/";

    @Value("${file.path}")
    private String filePath;

    @Resource
    private TokenUtil tokenUtil;

    @PostMapping("update")
    public JsonResult updateAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取项目classes/static的地址
        String path = filePath;
        // String fileName = file.getOriginalFilename(); // 获取文件名
        String fileOrigrec = file.getOriginalFilename();
        String ext = fileOrigrec.substring(fileOrigrec.lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString() + ext; // 获取文件名
        // 图片访问URI(即除了协议、地址和端口号的URL)
        String url_path = "image" + File.separator + fileName;
        String savePath = path + File.separator + url_path; // 图片保存路径
        File saveFile = new File(savePath);

        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        try {
            file.transferTo(saveFile); // 将临时存储的文件移动到真实存储路径下
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.error().codeAndMessage(HttpCodeEnum.ERROR);
        }

        // 返回图片访问地址
        return JsonResult.success().data("filePath", URL + url_path);
    }

}
